package cn.cycleif.admin.service;

import cn.cycleif.admin.pojo.vo.SysUserVO;
import cn.cycleif.app.mapper.RoleMapper;
import cn.cycleif.app.mapper.UserMapper;
import cn.cycleif.app.mapper.UserRoleMapper;
import cn.cycleif.app.service.UserService;
import cn.cycleif.entity.User;
import cn.cycleif.enums.ResultCodeEnum;
import cn.cycleif.enums.UserStatusEnum;
import cn.cycleif.util.PageUtil;
import cn.cycleif.util.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Date: 25/1/26-15:16
 * @Desc:
 */
@Service
public class AdminUserService extends ServiceImpl<UserMapper, User> {

  @Autowired
  private UserMapper     userMapper;
  @Autowired
  private RoleMapper     roleMapper;
  @Autowired
  private UserRoleMapper userRoleMapper;
  @Autowired
  private UserService    userService;

  public R<String> disable(Integer id) {
    return status(id, UserStatusEnum.DISABLE.getCode());
  }

  public R<String> status(Integer id, Integer status) {
    User user = userMapper.selectById(id);
    if (user == null) return R.error(ResultCodeEnum.ERROR_USER_NOT_EXIST);
    user.setStatus(UserStatusEnum.fromCode(status));
    userMapper.updateById(user);
    return R.success();
  }

  public R<Object> selectPage(Integer status) {
    Page<User>               page    = new Page<>(PageUtil.getPageNo(), PageUtil.getPageSize());
    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
    // 排除字段
    wrapper.select(User.class, user -> !user.getColumn().equals("password"));
    wrapper.eq(status != null, User::getStatus, status);
    Page<User>      userPage = userMapper.selectPage(page, wrapper);
    Page<SysUserVO> voPage   = new Page<>();
    voPage.setCurrent(userPage.getCurrent());
    voPage.setSize(userPage.getSize());
    voPage.setTotal(userPage.getTotal());
    voPage.setPages(userPage.getPages());
    // 添加其他信息
    List<User> records = userPage.getRecords();
    List<SysUserVO> sysUserVOS =
        records.stream().map(user -> {
                 SysUserVO vo = new SysUserVO();
                 vo.setUser(user);
                 vo.setRoles(userService.getRoleNames(user.getId()));
                 return vo;
               })
               .toList();
    voPage.setRecords(sysUserVOS);
    return R.success(voPage);
  }

}
